﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

namespace Rmlife.Common
{
    public class JsonHelp<T>
    {/// <summary>
        /// 将类型实例转换为Json字符串
        /// </summary>
        /// <param name="t">类型实例</param>
        /// <returns></returns>
        public static string ToJsonString(T t)
        {
            //string result = Newtonsoft.Json.JavaScriptConvert.SerializeObject(t);
            //JavaScriptSerializer ser = new JavaScriptSerializer();

            //新版本
            IsoDateTimeConverter a = new IsoDateTimeConverter();
            string result = JsonConvert.SerializeObject(t, a);
            return result;
        }

        /// <summary>
        /// 将Json字符串转换为类型实例
        /// </summary>
        /// <param name="jsonstring">字符串</param>
        /// <returns>类型</returns>
        public static T FromJsonString(string jsonstring)
        {
            //return Newtonsoft.Json.JavaScriptConvert.DeserializeObject<T>(jsonstring);

            //新版本            
            T t = JsonConvert.DeserializeObject<T>(jsonstring);
            return t;
        }

        /// <summary>
        /// 将List转换为字符串
        /// </summary>
        /// <param name="tlist">数据集</param>
        /// <returns>字符串</returns>
        public static string ToJsonString(List<T> tlist)
        {
            //string result = Newtonsoft.Json.JavaScriptConvert.SerializeObject(tlist);
            //return result;

            //新版本
            IsoDateTimeConverter a = new IsoDateTimeConverter();
            string result = JsonConvert.SerializeObject(tlist, Formatting.Indented, a);
            return result;
        }

        /// <summary>
        /// 将Json字符串转换为类型List集合
        /// </summary>
        /// <param name="jsonstring">字符串</param>
        /// <returns>类型集合</returns>
        public static List<T> GetList(string jsonstring)
        {
            //return Newtonsoft.Json.JavaScriptConvert.DeserializeObject<List<T>>(jsonstring);

            //新版本            
            List<T> list = JsonConvert.DeserializeObject<List<T>>(jsonstring);
            return list;
        }

    }
}
